package com.example.asa;

import com.example.asa.DatabaseUtil;
import org.mindrot.jbcrypt.BCrypt;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@WebServlet("/regservlet")
public class regservlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求编码
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        // 获取表单数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        String role = request.getParameter("role");

        // 参数验证
        if (username == null || username.isEmpty() || password == null || password.isEmpty() || role == null || role.isEmpty()) {
            request.setAttribute("error", "所有字段都是必填项");
            request.getRequestDispatcher("reg.jsp").forward(request, response);
            return;
        }

        // 密码长度验证
        if (password.length() < 6) {
            request.setAttribute("error", "密码长度至少为6位");
            request.getRequestDispatcher("reg.jsp").forward(request, response);
            return;
        }

        // 密码加密
        String hashedPassword = BCrypt.hashpw(password, BCrypt.gensalt());

        Connection conn = null;
        PreparedStatement stmt = null;

        try {
            // 获取数据库连接
            conn = DatabaseUtil.getConnection();
            conn.setAutoCommit(false); // 开启事务

            // 插入用户数据到数据库
            String sql = "INSERT INTO users (username, password, email, role) VALUES (?, ?, ?, ?)";
            stmt = conn.prepareStatement(sql);
            stmt.setString(1, username);
            stmt.setString(2, hashedPassword);
            stmt.setString(3, email);
            stmt.setString(4, role);

            // 添加调试输出
            System.out.println("注册信息 - 用户名: " + username + ", 角色: " + role);

            int rowsInserted = stmt.executeUpdate();

            if (rowsInserted > 0) {
                conn.commit(); // 提交事务

                // 注册成功，设置会话属性
                HttpSession session = request.getSession();
                session.setAttribute("user", username);
                session.setAttribute("role", role);

                // 添加调试输出
                System.out.println("注册成功 - 数据库写入的角色: " + role);

                // 重定向到用户列表页面
                response.sendRedirect("index.jsp");
            } else {
                conn.rollback(); // 回滚事务

                // 注册失败
                request.setAttribute("error", "注册失败，请重试");
                request.getRequestDispatcher("reg.jsp").forward(request, response);
            }
        } catch (SQLException e) {
            if (conn != null) {
                try {
                    conn.rollback(); // 出现异常时回滚
                    System.out.println("发生异常时回滚事务");
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }

            e.printStackTrace();
            request.setAttribute("error", "注册失败：" + e.getMessage());
            request.getRequestDispatcher("reg.jsp").forward(request, response);
        } finally {
            // 关闭数据库资源
            try {
                if (stmt != null) stmt.close();
                if (conn != null) conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
